import React, { ReactElement, ReactNode, useState, Fragment } from 'react'
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import Cook from 'js-cookie'
import { connect } from 'umi'

interface Props {
    children?: ReactNode,
    upLoad?: string,
    changeIntroduce: Function
}

function getBase64(img: any, callback: any) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file: any) {
    console.log(file.type)
    const isJpgOrPng = file.type === 'video/mp4'
    if (!isJpgOrPng) {
        message.error('请上传mp4格式');
    }
    const isLt10M = file.size / 1024 / 1024 < 20;
    // if (!isLt10M) {
    //     message.error('视频大于10MB!');
    // }
    return isJpgOrPng && isLt10M;
}

function Index({ changeIntroduce }: Props): ReactElement {
    const [loading, setLoading] = useState(false)
    const [imageUrl, setImageUrl] = useState("")

    const handleChange = (info: any) => {
        console.log(info.file)
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            changeIntroduce("video", info.file.response.url)
            getBase64(info.file.originFileObj, (imageUrl: string) => {
                setImageUrl(imageUrl)
                setLoading(false)
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    )
    return (
        <Fragment>
            <Upload
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="/api/upload/introduction" 
                headers={{
                    Authorization: Cook.get('token')
                }}
                beforeUpload={beforeUpload}
                onChange={handleChange}
            >
                {imageUrl ? <video src={imageUrl} style={{ width: '100%' }} /> : uploadButton}
            </Upload>
        </Fragment>
    )
}


export default connect(() => {
    return {

    }
}, (dispatch) => {
    return {
        changeIntroduce(classify: string, value: string) {
            dispatch({ type: "hero/changeIntroduce", classify, value })
        }
    }
})(Index)